package cn.ven.service;

import cn.ven.entity.Blog;
import cn.ven.entity.UserTagBlogContent;
import cn.ven.mapper.BlogMapper;

import cn.ven.tool.SessionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class BlogServiceImpl implements BlogService {

    @Autowired(required =false)
    BlogMapper blogMapper;


    @Override
    public void addBlog(Blog blog) {
        blog.setTcreate(new Date());
        blog.setCollectNum(0);
        blog.setReadingNum(0);
        blog.setLikeNum(0);
        blog.setClosed(1);
        blog.setUid(SessionUtil.getId());
        blogMapper.insert(blog);
    }

    @Override
    public void updateBlog(Blog blog) {
        blogMapper.updateById(blog);
    }

    @Override
    public void delBlog(int id) {
        blogMapper.deleteById(id);
    }

    @Override
    public List<Blog> findAll() {
        return blogMapper.selectAll();
    }

    @Override
    public UserTagBlogContent findUserTagBlogContent(int blogid) {
        Blog blog = blogMapper.selectById(blogid);
        blog.setReadingNum(blog.getReadingNum()+1);
        blogMapper.updateById(blog);
        UserTagBlogContent userTagBlogContent = blogMapper.findUserTagBlogContent(blogid);
        return userTagBlogContent;
    }

    @Override
    public Blog findById(int id) {
        return blogMapper.selectById(id);
    }

    @Override
    public List<UserTagBlogContent> findBlogByClosed(int closed) {
        LambdaQueryWrapper<Blog> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(Blog::getClosed,closed);
        List<Blog> blogs = blogMapper.selectList(queryWrapper);
        List<UserTagBlogContent> userTagBlogContents =new ArrayList<>();
        for (int i=0;i<blogs.size();i++){
            UserTagBlogContent userTagBlogContent = blogMapper.findUserTagBlogContent(blogs.get(i).getId());
            userTagBlogContents.add(userTagBlogContent);
        }
        return userTagBlogContents;
    }


}
